package cn.wolfcode.rbac.web.controller;

import cn.wolfcode.rbac.domain.vo.LoginInfoVo;
import cn.wolfcode.rbac.domain.vo.R;
import cn.wolfcode.rbac.sercurity.domian.LoginUser;
import cn.wolfcode.rbac.sercurity.service.TokenService;
import cn.wolfcode.rbac.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@Controller
@RequestMapping("/api")
@CrossOrigin(allowCredentials = "true")
public class LoginApiController {

    @Autowired
    private ILoginService loginService;
    @Autowired
    private TokenService tokenService;

    @GetMapping("/code")
    @ResponseBody
    public R code() {
        return R.ok(loginService.getCode());
    }
    @PostMapping("/login")
    @ResponseBody
    public R login(@RequestBody LoginInfoVo loginInfoVo) {
        String token;
        try {
            token = loginService.login(loginInfoVo);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(e.getMessage());
        }
        return R.ok("登录成功",token);
    }

    @GetMapping("/logout")
    @ResponseBody
    public R logout(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        loginService.logout(loginUser.getUuid());
        return R.ok("退出成功");
    }
}
